import { Card, Col, Row } from 'antd';
import { useState } from 'react';
import { DndProvider, useDrag, useDrop } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';

// 拖拽元素组件
interface DraggableItemProps {
  id: number;
  text: string;
  index: number;
  moveItem: (fromIndex: number, toIndex: number) => void;
}

const DraggableItem: React.FC<DraggableItemProps> = ({
  id,
  text,
  index,
  moveItem,
}) => {
  const [{ isDragging }, drag] = useDrag(() => ({
    type: 'ITEM',
    item: { id, index },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  }));

  const [, drop] = useDrop({
    accept: 'ITEM',
    hover: (draggedItem: { id: number; index: number }) => {
      if (draggedItem.index !== index) {
        moveItem(draggedItem.index, index);
        draggedItem.index = index; // 立即更新索引
      }
    },
  });

  return (
    <div
      ref={(node) => drag(drop(node))}
      style={{ opacity: isDragging ? 0.5 : 1 }}
    >
      <Card hoverable style={{ marginBottom: 8 }}>
        {text} (ID: {id})
      </Card>
    </div>
  );
};

// 容器组件
const SortableContainer = () => {
  const [items, setItems] = useState<{ id: number; text: string }[]>([
    { id: 1, text: 'Item 1' },
    { id: 2, text: 'Item 2' },
    { id: 3, text: 'Item 3' },
  ]);

  const moveItem = (fromIndex: number, toIndex: number) => {
    const newItems = [...items];
    const [removed] = newItems.splice(fromIndex, 1);
    newItems.splice(toIndex, 0, removed);
    setItems(newItems);
  };

  return (
    <DndProvider backend={HTML5Backend}>
      <Row gutter={16}>
        <Col span={8}>
          <h3>可排序列表</h3>
          {items.map((item, index) => (
            <DraggableItem
              key={item.id}
              index={index}
              id={item.id}
              text={item.text}
              moveItem={moveItem}
            />
          ))}
        </Col>

        <Col>
          <pre>{JSON.stringify(items, null, 2)}</pre>
        </Col>
      </Row>
    </DndProvider>
  );
};

export default SortableContainer;
